package org.dromara.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.cssUtils.RedisServiceUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.SkExperience;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkExperienceMapper;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.BfExperienceLogBo;
import org.dromara.app.domain.vo.BfExperienceLogVo;
import org.dromara.app.domain.BfExperienceLog;
import org.dromara.app.mapper.BfExperienceLogMapper;
import org.dromara.app.service.IBfExperienceLogService;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 经验记录LOGService业务层处理
 *
 * @author Evacuation
 * @date 2024-08-07
 */
@RequiredArgsConstructor
@Service
public class BfExperienceLogServiceImpl implements IBfExperienceLogService {

    private final BfExperienceLogMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    private final SkExperienceMapper skExperienceMapper;

    /**
     * 查询经验记录LOG
     *
     * @param id 主键
     * @return 经验记录LOG
     */
    @Override
    public BfExperienceLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询经验记录LOG列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 经验记录LOG分页列表
     */
    @Override
    public TableDataInfo<BfExperienceLogVo> queryPageList(BfExperienceLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BfExperienceLog> lqw = buildQueryWrapper(bo);
        Page<BfExperienceLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的经验记录LOG列表
     *
     * @param bo 查询条件
     * @return 经验记录LOG列表
     */
    @Override
    public List<BfExperienceLogVo> queryList(BfExperienceLogBo bo) {
        LambdaQueryWrapper<BfExperienceLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BfExperienceLog> buildQueryWrapper(BfExperienceLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BfExperienceLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, BfExperienceLog::getUserId, bo.getUserId());
        lqw.eq(bo.getType() != null, BfExperienceLog::getType, bo.getType());
        lqw.eq(bo.getSoure() != null, BfExperienceLog::getSoure, bo.getSoure());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), BfExperienceLog::getContent, bo.getContent());
        lqw.orderByDesc(BfExperienceLog::getCreateTime);
        return lqw;
    }

    /**
     * 新增经验记录LOG
     *
     * @param bo 经验记录LOG
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BfExperienceLogBo bo) {
        BfExperienceLog add = MapstructUtils.convert(bo, BfExperienceLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改经验记录LOG
     *
     * @param bo 经验记录LOG
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BfExperienceLogBo bo) {
        BfExperienceLog update = MapstructUtils.convert(bo, BfExperienceLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BfExperienceLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除经验记录LOG信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public String getKeyValue(String title) {
        return selectConfigByKey(CssUtils.getJingYanConfig("自己发布组局").toString());
    }

    /**
     * 更新经验值
     * @param userId
     * @param number
     * @param title
     */
    @Async
    @Override
    public void addLog(Long userId, String number,String title) {
        //增加log
        BfExperienceLog log = new BfExperienceLog();
        log.setContent(title);
        log.setUserId(userId);
        log.setNumber(Long.valueOf(number));
        //更新用户经验值和等级
        skAppUserMapper.updateExperience(Long.valueOf(number),userId);
        baseMapper.insert(log);
    }

    @Cacheable(cacheNames = CacheNames.SYS_CONFIG, key = "#configKey")
    public String selectConfigByKey(String configKey) {
        Object object = RedisUtils.getCacheMapValue(CacheNames.SYS_CONFIG,configKey);
        if (object==null){
            String value = baseMapper.selectValue(configKey);
            if (ObjectUtil.isNotNull(value)) {
                RedisUtils.setCacheMapValue(CacheNames.SYS_CONFIG,configKey,value);
                return value;
            }
        }else{
            return object.toString();
        }
        return StringUtils.EMPTY;
    }

}
